import 'dart:async';
import 'package:base_lib/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class GenderPicker {
  static Future<GenderBean> showGenderPicker({
    @required BuildContext context,
    double height = 400.0,
    List<GenderBean> genderList,
    GenderBean selectedItem,
    ThemeData theme,
    // PickerRoute params
    bool barrierDismissible = false,
    double barrierOpacity = 0.5,
    ItemWidgetBuilder itemBuilder,
    double itemExtent,
    Widget cancelWidget,
    Widget confirmWidget,
  }) {
    return Navigator.of(context, rootNavigator: true).push(
      new PickerRoute(
          theme: theme ?? Theme.of(context),
          canBarrierDismiss: barrierDismissible,
          barrierOpacity: barrierOpacity,
          barrierLabel:
              MaterialLocalizations.of(context).modalBarrierDismissLabel,
          child: GenderPickerView(
            height: height,
            itemExtent: itemExtent,
            itemBuilder: itemBuilder,
            cancelWidget: cancelWidget,
            confirmWidget: confirmWidget,
            genderList: genderList,
            selectedItem: selectedItem,
          )),
    );
  }
}

class GenderBean<T> {
  String name;
  int code;
  T data;

  GenderBean(this.name, this.code, {this.data});

  @override
  operator ==(other) {
    if (other is! GenderBean) {
      return false;
    }
    return name == other.name && code == other.code;
  }

  @override
  int get hashCode => super.hashCode;
}

///性别选择器
class GenderPickerView extends StatefulWidget {
  final List<GenderBean> genderList;

  final GenderBean selectedItem;

  final ItemWidgetBuilder itemBuilder;

  /// ios选择框的高度. 配合 itemBuilder中的字体使用.
  final double itemExtent;

  /// 容器高度
  final double height;

  /// 取消按钮的Widget
  /// 当用户设置该属性. 会优先使用用户设置的widget, 否则使用代码中默认的文本, 使用primary主题色
  final Widget cancelWidget;

  final Widget confirmWidget;

  /// 确认按钮的widget
  /// 当用户设置该属性. 会优先使用用户设置的widget, 否则使用代码中默认的文本, 使用primary主题色
  GenderPickerView({
    this.selectedItem,
    this.genderList,
    this.itemBuilder,
    this.itemExtent = 40,
    this.height = 245,
    this.cancelWidget,
    this.confirmWidget,
  }) : assert(!(itemBuilder != null && itemExtent == null),
            "\ritemExtent could't be null if itemBuilder exits");

  _GenderPickerState createState() => _GenderPickerState();
}

class _GenderPickerState extends State<GenderPickerView> {
  List<GenderBean> genderList;

  GenderBean selectedItem;

  Timer _changeTimer;
  FixedExtentScrollController genderController;
  GenderBean resultGender;

  @override
  void initState() {
    super.initState();

    genderList = widget.genderList ??
        [
          GenderBean(Utils.returnGenderByInt(0), 0),
          GenderBean(Utils.returnGenderByInt(1), 1),
          GenderBean(Utils.returnGenderByInt(2), 2)
        ];

    selectedItem =
        widget.selectedItem ?? GenderBean(Utils.returnGenderByInt(1), 1);

    _initController();
  }

  void dispose() {
    genderController.dispose();
    if (_changeTimer != null && _changeTimer.isActive) {
      _changeTimer.cancel();
    }
    super.dispose();
  }

  // 初始化controller, 为了使给定的默认值, 在选框的中心位置
  void _initController() {
    genderController = new FixedExtentScrollController(
        initialItem:
            genderList.indexWhere((GenderBean g) => g == selectedItem));
  }

  // 加入延时处理, 减少构建树的消耗
  _onGenderChange(GenderBean _gender) {
    if (_changeTimer != null && _changeTimer.isActive) {
      _changeTimer.cancel();
    }
    _changeTimer = new Timer(Duration(milliseconds: 500), () {
      resultGender = _gender;
    });
  }

  GenderBean _buildResult() {
    return resultGender;
  }

  Widget _bottomBuild() {
    return new Container(
        width: double.infinity,
        color: Theme.of(context).scaffoldBackgroundColor,
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            new Row(
              children: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.pop(context, _buildResult());
                  },
                  child: widget.cancelWidget ??
                      new Text(
                        '取消',
                        style: new TextStyle(
                          color: Theme.of(context).primaryColor,
                        ),
                      ),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.pop(context, _buildResult());
                  },
                  child: widget.confirmWidget ??
                      new Text(
                        '确定',
                        style: new TextStyle(
                          color: Theme.of(context).primaryColor,
                        ),
                      ),
                ),
              ],
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
            ),
            Expanded(
              child: new Row(
                children: <Widget>[
                  5.hGapDp,
                  MyWheelPicker(
                    key: Key('gender'),
                    height: widget.height,
                    controller: genderController,
                    itemBuilder: widget.itemBuilder,
                    itemExtent: widget.itemExtent,
                    value: selectedItem.name,
                    itemList: genderList.map((v) => v.name).toList(),
                    changed: (index) {
                      _onGenderChange(genderList[index]);
                    },
                  ),
                  5.hGapDp,
                ],
              ),
            )
          ],
        ));
  }

  Widget build(BuildContext context) {
    final route = InheritRouteWidget.of(context).router;
    return new AnimatedBuilder(
      animation: route.animation,
      builder: (BuildContext context, Widget child) {
        return new CustomSingleChildLayout(
          delegate: WrapLayout(
              progress: route.animation.value, height: widget.height),
          child: new GestureDetector(
            child: new Material(
              color: Colors.transparent,
              child:
                  new Container(width: double.infinity, child: _bottomBuild()),
            ),
          ),
        );
      },
    );
  }
}
